package by.gusto.afisha.model;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import by.gusto.afisha.db.HelperFactory;
import by.gusto.afisha.net.ServerType;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "Categories")
public class Category {

	public static final String NAME_FIELD = "name";
	public static final String URL_FIELD = "url";
	public static final String ID_FIELD = "external_id";
	public static final String SERVER_ID_FIELD = "server_id";
	public static final String COUNT_FIELD = "count";
	
	@DatabaseField(generatedId = true)
	public transient int id;
	
	@DatabaseField(dataType = DataType.STRING, columnName = NAME_FIELD)
	public String name;
	
	@DatabaseField(dataType = DataType.STRING, columnName = URL_FIELD)
	public String url;
	
	@DatabaseField(dataType = DataType.INTEGER, columnName = ID_FIELD)
	public int externalId;
	
	@DatabaseField(dataType = DataType.INTEGER, columnName = SERVER_ID_FIELD)
	public int serverId;
	
	@DatabaseField(dataType = DataType.INTEGER, columnName = COUNT_FIELD)
	public int count;
	
	public Category() { }
	
	public Category(final String string) {
		name = string;
	}

	public static List<Category> getAll() {
		List<Category> categories = null;
		try {
			categories = HelperFactory.GetHelper().getCategoryDAO().queryForAll();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		return categories;
	}

	public static void save(final ArrayList<Category> categories, final ServerType type) {
		Dao<Category, String> dao = null;
		try {
			dao = HelperFactory.GetHelper().getCategoryDAO();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		for (Category category : categories) {
			category.serverId = type.getId();
			try {
				
				List<Category> oldCategories = dao.queryBuilder().where().eq(ID_FIELD, category.externalId).query();
				if (oldCategories.size() > 0) {
					category.id = oldCategories.get(0).id;
					dao.update(category);
				} else {
					dao.create(category);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static int findId(final Category category) {
		Dao<Category, String> dao = null;
		try {
			dao = HelperFactory.GetHelper().getCategoryDAO();
			List<Category> oldCategories = dao.queryBuilder().where().eq(ID_FIELD, category.externalId).query();
			if (oldCategories.size() > 0) {
				return oldCategories.get(0).id;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
}
